package com.yan.programercode.chapter_1.question_2;

import java.util.Stack;

/**
 * 问题：
 * 编写一个类，用两个栈实现队列，实现队列的基本操作，add、poll、peek
 * 解答：
 * 栈的特点是先进后出，队列的特点是先进先出。我们用两个栈正好可以把顺序反过来实现类似队列的操作。
 *
 */
public class TwoStackQueue {

	private Stack<Integer> stackPush;
	private Stack<Integer> stackPop;
	
	public TwoStackQueue() {
		stackPush = new Stack<Integer>();
		stackPop = new Stack<Integer>();
	}
	
	public void add(int pushInt){
		stackPush.push(pushInt);
	}
	
	public int poll(){
		if(stackPush.empty() && stackPop.empty()){
			throw new RuntimeException("Queue is empty.");
		}else if (stackPop.empty()) {
			while (!stackPush.empty()) {
				stackPop.push(stackPush.pop());
			}
		}
		return stackPop.pop();
	}
	
	public int peek(){
		if(stackPush.empty() && stackPop.empty()){
			throw new RuntimeException("Queue is empty.");
		}else if (stackPop.empty()) {
			while (!stackPush.empty()) {
				stackPop.push(stackPush.pop());
			}
		}
		return stackPop.peek();
	}
}
